#include<iostream>
#include<unistd.h>
#include<cstring>
#include <sys/types.h>
#include <sys/wait.h>
#include<string>
const int size = 512;
std::string GetOtherMessage()
{
    static int cnt = 0;
    std::string CntString = std::to_string(cnt++);
    pid_t pid = getpid();
    std::string PidString = std::to_string(pid);
    std::string message("cnt = ");
    message+=CntString;
    message+="my pid = ";
    message+=PidString;
    return message;
}
void SonProcessLoad(int wfd)
{
    std::string message = "i am child process,";
    while(true)
    {
        std::string info = message + GetOtherMessage();
        //send mesage...
        write(wfd,info.c_str(),info.size());
        sleep(1);
    }
}

void FatherProcessLoad(int rfd)
{
    char inbuff[size];
    while(true)
    {
        //read message...
        ssize_t n = read(rfd,inbuff,sizeof inbuff-1);
        if(n > 0)
        {
             inbuff[n] = 0;
             std::cout<<"Father read message = "<<inbuff<<std::endl;
        }
    }
}
int main()
{    
    //创建匿名管道
    int pipefd[2];
    int n = pipe(pipefd);
    if(n!=0)
    {
        std::cerr<<"errno = "<<errno<<"stringerrno："<<strerror(errno)<<std::endl;
        exit(1);
    }
    std::cout<<"pipefd[0] = "<<pipefd[0]<<" pipefd[2] = "<<pipefd[1]<<std::endl;
    //创建父子进程
    pid_t id = fork();
    if(id == 0)
    {
        //子进程
        std::cout<<"关闭读取文件fd,准备发送信息..."<<std::endl;
        sleep(1);
        close(pipefd[0]);
        SonProcessLoad(pipefd[1]);
        close(pipefd[1]);
        exit(0);
    }
    sleep(1);
    std::cout<<"关闭写入文件fd,正在接收信息..."<<std::endl;
    close(pipefd[1]);
    FatherProcessLoad(pipefd[0]);
    close(pipefd[0]);
    //父进程等待
    int status = 0;
    pid_t pd = waitpid(id,&status,0);
    if(pd < 0)
    {
        std::cout<<"父进程等待失败!"<<std::endl;
        exit(1);
    }
    return 0;
}
